import axios from 'axios'

const service = axios.create({
  baseURL: 'api', // api的base_url
  timeout: 10000, // 请求超时时间
  withCredentials: true
})

// request拦截器
service.interceptors.request.use(config => {
  config.headers = {
    'Content-Type': 'application/json'
  }
  return config
}, error => {
  return Promise.reject(error)
})

service.interceptors.response.use(response => {
  const res = response.data
  if (res.code != '0') {
    // 错误
  } else {
    // 正确
    return res
  }
})

const getConfig = (params, level = 0) => {
  const paramsTemp = params || {}
  const config_ = {
    params: paramsTemp
  }
  return config_
}

// 封装常用方法
const get = (url, params) => {
  return service.get(url, getConfig(params))
}
const post = (url, params) => {
  return service.post(url, params)
}
const DELETE = (url, params) => {
  return service.delete(url, params)
}

export { get, post, DELETE }